<template>
	<div ref="title" class="title" :style="style">
		<div>
			<slot></slot>
		</div>
	</div>
</template>

<script>
export default {
	name: "titleScrolling",
	props: {
		interval: {
			default: 10
		}
	},
	data() {
		return {
			titleMove: 0,
			titleInterval: 2,
			observer: null,
			observerTimer: null
		};
	},
	computed: {
		style() {
			return {
				"--titleMove": `${this.titleMove}px`,
				"--titleMoveTime": `${this.titleInterval / 2}s`
			};
		}
	},
	mounted() {
		this.addObserver();
	},
	beforeDestroy() {
		if (this.observer) {
			this.observer.disconnect();
		}
	},
	methods: {
		addObserver() {
			try {
				const parent = this.$el;
				if (!parent) {
					throw new Error();
				}
				const child = parent.firstChild;
				const getMove = () => {
					const move = child.offsetWidth - parent.offsetWidth;
					if (move > 0) {
						this.titleMove = -move - 10;
					} else {
						this.titleMove = 0;
					}
					this.titleInterval = this.interval;
				};
				if (this.observer) {
					this.observer.disconnect();
				}
				// @ts-ignore
				this.observer = new ResizeObserver(getMove);

				this.observer.observe(parent);
				this.observer.observe(child);
				getMove();
			} catch (error) {
				this.observerTimer = setTimeout(() => {
					this.addObserver();
				}, 1000);
			}
		}
	}
};
</script>
<style scoped lang='scss'>
.title {
	position: relative;
	overflow: hidden;
	& > div {
		animation: moveText var(--titleMoveTime) linear 0.25s infinite
			alternate-reverse;
		width: fit-content;
		// &:hover {
		// 	animation-play-state: paused;
		// }
	}
}
@keyframes moveText {
	0%,
	20% {
		transform: translateX(var(--titleMove));
	}
	80%,
	100% {
		transform: translateX(0%);
	}
}
</style>
